<template>
  <div>
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="输入关键字搜索"
        clearable
        @clear="defaultExpandedKeys = []"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-button type="danger" @click="handleDeleteAll" style="margin: 16px 0"> 全局删除 </el-button>

    <!-- 加载显示区域 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon is-loading"><Loading /></el-icon>
      <span class="loading-text">加载中...</span>
    </div>

    <el-tree
      v-else
      :data="filteredData"
      :props="defaultProps"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandedKeys"
      @node-click="handleNodeClick"
      node-key="label"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <div
            class="node-left"
            @click.stop="handleLeftClick(data)"
            v-html="highlightText(node.label)"
          ></div>
          <div class="node-right">
            <el-icon
              v-if="node.childNodes && node.childNodes.length > 0"
              @click.stop="handleExpandClick(node)"
              class="expand-icon"
            >
              <ArrowDownBold v-if="node.expanded" />
              <ArrowRightBold v-else />
            </el-icon>
            <el-icon class="delete-icon" @click.stop="handleDeleteNode(data)">
              <Delete />
            </el-icon>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, watch } from 'vue';
  import { ElTree, ElIcon, ElMessageBox, ElButton, ElInput } from 'element-plus';
  import { ArrowDownBold, ArrowRightBold, Delete, Search, Loading } from '@element-plus/icons-vue';
  import { sendMultipleFilesToUnity } from '/@/views/DigitalTwin/newleft/service/unityService';
  import store from '/@/views/DigitalTwin/newleft/manage/store';
  import { deleteEntity, getDevice, getSharedScope } from '/@/api/thingsborad/entity/entity';
  import { debounce } from 'lodash-es';
  import { deviceInfoItem } from '/@/api/thingsborad/entity/model/entityModel';

  const data = ref<Tree[]>([]);
  // 加载状态
  const loading = ref(false);
  // 修复：根据当前选中的方案来获取节点数据
  const nodes = computed(() => {
    // 检查是否有选中的方案
    const selectedIssue = store.state.selectedIssue;
    if (selectedIssue && Array.isArray(store.state.nodeData)) {
      // 返回当前方案的节点数据
      return store.state.nodeData;
    }
    // 默认返回空数组
    return [];
  });

  interface Tree {
    label: string;
    children?: Tree[];
    originData?: any;
    isVirtual?: boolean; // 新增虚拟节点标识
    missingParent?: boolean; // 新增缺失父节点标识
  }

  const initTreeData = async () => {
    let devicesAttributes: Record<string, Record<string, Record<string, any>>> | null = store.state
      .devicesAttributes;
    if (!devicesAttributes) {
      const deviceInfoItem: deviceInfoItem = await getDevice(
        store.state.selectedIssue?.toName + '-设备总览',
      );
      const attributesResponse = await getSharedScope({
        entityType: deviceInfoItem.id.entityType,
        entityId: deviceInfoItem.id.id,
        scope: 'SHARED_SCOPE',
        responseDataType: 'values',
      });
      devicesAttributes = store.state.devicesAttributes = attributesResponse[0].value as Record<
        string,
        Record<string, Record<string, any>>
      >;
    }
    // 设置加载状态为true
    loading.value = true;
    try {
      // 使用 devicesAttributes 构建树结构
      const buildTreeFromAttributes = () => {
        // 创建父子关系映射
        const childrenMap = new Map<string, any[]>();

        // 初始化根节点
        childrenMap.set('Model', []);

        // 遍历所有设备属性，建立父子关系
        Object.keys(devicesAttributes).forEach((deviceName) => {
          const deviceAttrs = devicesAttributes[deviceName];
          // 获取父节点名称，默认为 'Model'
          const parentName =
            deviceAttrs.Parent && deviceAttrs.Parent !== '' ? deviceAttrs.Parent : 'Model';

          // 如果父节点不存在，创建它
          if (!childrenMap.has(parentName)) {
            childrenMap.set(parentName, []);
          }

          // 将当前设备添加到父节点的子节点列表中
          childrenMap.get(parentName)!.push({
            toName: deviceName,
            ...deviceAttrs,
          });
        });

        // 递归构建树节点
        const buildTree = (nodeName: string): Tree => {
          const children = childrenMap.has(nodeName)
            ? childrenMap.get(nodeName)!.map((child) => buildTree(child.toName))
            : [];

          return {
            label: nodeName,
            children: children,
            originData: devicesAttributes[nodeName],
          };
        };

        // 构建根节点下的所有节点
        const rootChildren = childrenMap.get('Model') || [];
        return rootChildren.map((child) => buildTree(child.toName));
      };

      // 生成树数据
      data.value = buildTreeFromAttributes();
    } catch (error) {
      console.error('[初始化失败]', error);
      data.value = [];
    } finally {
      // 无论成功还是失败，都将加载状态设置为false
      loading.value = false;
    }
  };

  // 修复：监听节点数据变化并重新初始化树
  watch(
    () => store.state.nodeData,
    () => {
      initTreeData();
    },
    { immediate: true },
  );

  const defaultProps = {
    children: 'children',
    label: 'label',
  };

  //搜索功能
  const searchQuery = ref('');
  const defaultExpandedKeys = ref<(string | number)[]>([]);

  watch(
    searchQuery,
    debounce((newVal) => {
      if (newVal) {
        // 强制展开根节点确保搜索可见
        const baseKeys = data.value.map((n) => n.label);
        const matchKeys = expandParent(data.value, newVal);
        defaultExpandedKeys.value = [...new Set([...baseKeys, ...matchKeys])];
      } else {
        defaultExpandedKeys.value = [];
      }
    }, 300),
    { deep: true },
  );
  // 过滤方法
  const filterNode = (value: string, data: Tree): boolean => {
    if (!value) return true;
    return data.label.includes(value);
  };

  // 展开所有匹配节点的父节点
  const expandParent = (nodes: Tree[], value: string): string[] => {
    const expandedKeys: string[] = [];

    const traverse = (nodeList: Tree[]): boolean => {
      return nodeList.some((node) => {
        // 当前节点是否匹配
        const selfMatch = node.label.includes(value);

        // 递归检查子节点
        let childMatch = false;
        if (node.children) {
          childMatch = traverse(node.children);
        }

        // 满足展开条件
        if (selfMatch || childMatch) {
          expandedKeys.push(node.label);
          return true;
        }
        return false;
      });
    };

    traverse(nodes);
    return expandedKeys;
  };

  // 过滤后的树数据
  const filteredData = computed(() => {
    if (!searchQuery.value) return data.value;

    const filter = (nodes: Tree[]): Tree[] => {
      return nodes
        .filter((node) => {
          const match = filterNode(searchQuery.value, node);
          if (node.children) {
            const children = filter(node.children);
            return children.length > 0 || match;
          }
          return match;
        })
        .map((node) => ({
          ...node,
          children: node.children ? filter(node.children) : undefined,
        }));
    };

    return filter(data.value);
  });

  // 高亮显示匹配文本
  const highlightText = (text: string) => {
    const query = searchQuery.value;
    if (!query) return text;
    return text.replace(new RegExp(`(${query})`, 'gi'), '<span class="highlight">$1</span>');
  };

  // 删除处理方法
  const handleDeleteNode = async (data: Tree) => {
    try {
      await ElMessageBox.confirm('确认删除该节点？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });

      if (data.originData?.to) {
        await deleteEntity({
          entityType: 'device',
          entityId: data.originData.to.id,
        });

        // 更新节点数据（过滤已删除节点）
        const currentNodes = nodes.value.filter((n) => n.to.id !== data.originData.to.id);
        // 更新store中的节点数据
        store.state.nodeData = currentNodes;
        await initTreeData();
      }
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  // 全局删除方法
  const handleDeleteAll = async () => {
    try {
      await ElMessageBox.confirm('确认删除所有节点？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });

      // 收集所有节点ID（过滤无效节点）
      const collectIds = (nodes: Tree[]): string[] => {
        return nodes.reduce((acc: string[], node) => {
          if (node.originData?.to?.id) {
            acc.push(node.originData.to.id);
          }
          if (node.children) {
            acc.push(...collectIds(node.children));
          }
          return acc;
        }, []);
      };

      const ids = collectIds(data.value);
      await Promise.all(ids.map((id) => deleteEntity({ entityType: 'device', entityId: id })));

      // 清空节点数据
      store.state.nodeData = [];
      await initTreeData();
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const handleNodeClick = (data: Tree) => {
    // 默认点击处理（现在由自定义区域处理）
  };

  const handleLeftClick = (data: Tree) => {
    sendMultipleFilesToUnity(data);
  };

  const handleExpandClick = (node: any) => {
    node.expanded = !node.expanded;
  };
</script>
<style scoped>
  .highlight {
    color: #ffd04b;
    font-weight: bold;
  }

  .search-container {
    margin-bottom: 16px;
    max-width: 300px;
  }

  .custom-tree-node {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding-right: 8px;
  }

  .node-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .delete-icon:hover {
    color: #ff7875;
  }
  /* 新增删除按钮样式 */
  .delete-icon {
    margin-left: 8px;
    color: #ff4d4f;
    transition: color 0.2s;
  }

  .delete-icon:hover {
    color: #ff7875;
  }

  .node-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  :deep(.el-tree) {
    background: #1e2430;
    color: white;
  }

  :deep(.el-tree-node__content) {
    height: auto;
    background: #1e2430 !important;
    width: 14vw;
  }

  :deep(.el-tree-node__content:hover) {
    background-color: #4583ff !important;
  }

  .custom-tree-node {
    display: flex;
    width: 100%;
    align-items: center;
    padding: 8px 0;
  }

  .node-left {
    flex: 0 0 80%;
    cursor: pointer;
    padding-left: 8px;
  }

  .node-right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    padding-right: 8px;
    cursor: pointer;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none; /* 隐藏默认箭头 */
  }

  /* 加载样式 */
  .loading-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }

  .loading-icon {
    font-size: 24px;
    color: #4583ff;
    animation: rotating 2s linear infinite;
  }

  .loading-text {
    margin-left: 10px;
    color: #4583ff;
    font-size: 14px;
  }

  @keyframes rotating {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .expand-icon.no-children {
    opacity: 0.3;
    cursor: not-allowed;
  }
</style>
